import { defineStore } from "pinia";
import { getUserInfo } from "../api/user";
import { getEmployeeResource } from "../api/roleResource";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: localStorage.getItem("token") || "",
    userInfo: JSON.parse(localStorage.getItem("userInfo") || "{}"),
    permissions: JSON.parse(localStorage.getItem("permissions") || "[]"),
  }),

  actions: {
    setToken(token) {
      this.token = token;
      localStorage.setItem("token", token);
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      localStorage.setItem("userInfo", JSON.stringify(userInfo));
    },
    setPermissions(permissions) {
      this.permissions = permissions;
      localStorage.setItem("permissions", JSON.stringify(permissions));
    },
    logout() {
      this.token = "";
      this.userInfo = {};
      this.permissions = [];
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("permissions");
    },
    // 获取用户信息和权限
    async getUserPermissions() {
      try {
        // 如果没有用户信息，先获取用户信息
        if (Object.keys(this.userInfo).length === 0) {
          const userRes = await getUserInfo();
          this.setUserInfo(userRes.data);
        }
        
        // 通过员工ID获取所有角色
        if (this.userInfo.id) {
          const employeeResources = await getEmployeeResource();
          // 设置合并后的权限
          this.setPermissions(employeeResources.data);
        }
        
        return {
          userInfo: this.userInfo,
          permissions: this.permissions
        };
      } catch (error) {
        console.error('获取用户信息和权限失败:', error);
        throw error;
      }
    },
  },
});
